//
//  ex.swift
//  st
//
//  Created by 罗天杭 on 2022/8/18.
//

import Foundation
import SwiftUI
import CoreML

func imagelth(multiArray: MLMultiArray) -> UIImage {
    let shape = multiArray.shape
    let width = shape[2].intValue
    let height = shape[3].intValue
    let bitsPerComponent = 8
    let depth = 3
    let bitsPerPixel = bitsPerComponent * depth
    let bytesPerRow = width*depth
    
    let dataPointer = multiArray.dataPointer
    let dataCount = multiArray.count
    let data32Arr  = dataPointer.bindMemory(to: UInt32.self, capacity: dataCount);
    
    let outputLength = dataCount
    let outputArr = UnsafeMutableRawPointer.allocate(byteCount: outputLength, alignment: 0).bindMemory(to: UInt8.self, capacity: outputLength)
    
    
    
    for i in 0 ..< dataCount/3{
        let this_r = CGFloat(data32Arr[i])/255/255/255
        let this_g = CGFloat(data32Arr[dataCount/3+i])/255/255/255
        let this_b = CGFloat(data32Arr[dataCount*2/3+i])/255/255/255
        
        let rgb = UIColor(red: this_r, green: this_g, blue: this_b, alpha: 1)
        
        let components = rgb.cgColor.components
        
        outputArr[i * depth + 0] = UInt8(components![0] )
        outputArr[i * depth + 1] = UInt8(components![2] )
        outputArr[i * depth + 2] = UInt8(components![1] )

        
    }
    
    let dataRef = CFDataCreate(nil, outputArr, outputLength)
    let dataProviderRef = CGDataProvider(data: dataRef!)
    
    let ref = CGImage(width: width, height: height, bitsPerComponent: bitsPerComponent, bitsPerPixel: bitsPerPixel, bytesPerRow: bytesPerRow, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: .byteOrder16Big, provider: dataProviderRef!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
    let newImage = UIImage(cgImage: ref!)
    return newImage
}

